package cmd

import (
	"car-thirdparty-api/internal/controller/booking"
	"car-thirdparty-api/internal/controller/car_search"
	"car-thirdparty-api/internal/controller/message"
	"car-thirdparty-api/internal/controller/passInfo"
	"context"
	"net/http"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"

	"car-thirdparty-api/internal/controller/hello"
)

func MiddlewareAuthCheck(r *ghttp.Request) {
	expectedKey := "X-Custom-Key"
	expectedValue := g.Cfg().MustGet(r.GetCtx(), "auth.key").String()

	actualValue := r.Header.Get(expectedKey)
	if actualValue != expectedValue {
		g.Log().Error(r.GetCtx(), "Invalid or missing custom header key")
		r.Response.WriteJsonExit(g.Map{
			"code":    http.StatusForbidden,
			"message": "非法访问",
		})
		return
	}

	r.Middleware.Next()
}

func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			//s.Group("/api/car", func(group *ghttp.RouterGroup) {
			//	group.Middleware(MiddlewareCORS)
			//	group.GET("/search", carSearch.CarSearch)
			//})

			s.Group("/api", func(group *ghttp.RouterGroup) {
				group.Middleware(MiddlewareCORS)
				//group.GET("/search", carSearch.CarSearch)
				//group.GET("/app/search", carSearch.CarAppSearch)
				group.Middleware(MiddlewareAuthCheck) // 添加新的中间件
				group.Middleware(ghttp.MiddlewareHandlerResponse)
				group.Bind(
					hello.NewV1(),
					booking.NewV1(),
					passInfo.NewV1(),
					message.NewV1(),
					car_search.NewV1(),
				)
			})
			s.Run()
			return nil
		},
	}
)
